package com.aliyun.messagemgt.util;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.auth.DefaultCredentials;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

/**
 * Created with IDEA
 *
 * @author:zhangxingxing 0027012120
 * @date:2019/1/31
 * @time:17:59
 */
public class OSSUtil {

    private static String endpoint = null;
    private static String keyId = null;
    private static String keySecret = null;
    private static String bucketName = null;
    private static Integer expiration = 7300;
    private static String folder = "";
    private static Logger logger = LoggerFactory.getLogger(OSSUtil.class);

    public static void setup(String endpoint, String keyId, String keySecret, String bucketName) {
        OSSUtil.endpoint = endpoint;
        OSSUtil.keyId = keyId;
        OSSUtil.keySecret = keySecret;
        OSSUtil.bucketName = bucketName;
    }

    public static String uploadInputStream(InputStream inputStream, String meidaType, String uuid) throws IOException {
        ClientConfiguration config = new ClientConfiguration();
        config.setSupportCname(false);
        // OSSClient ossClient = new OSSClient(endpoint, keyId, keySecret, config);
        DefaultCredentials defaultCredentials = new DefaultCredentials(keyId, keySecret);
        DefaultCredentialProvider defaultCredentialProvider = new DefaultCredentialProvider(defaultCredentials);
        OSSClient ossClient = new OSSClient(endpoint, defaultCredentialProvider, config);
        String fileName = folder + uuid + "." + meidaType;
        ossClient.putObject(bucketName, fileName, inputStream);
        Date expirationTime = new Date(System.currentTimeMillis() + 86400000L * (long) expiration);
        // 生成以GET方法访问的签名URL，访客可以直接通过浏览器访问相关内容。
        String resurl = ossClient.generatePresignedUrl(bucketName, fileName, expirationTime).toString();
        ossClient.shutdown();
        return resurl;
    }

}
